<?php

declare(strict_types=1);

namespace AdminBundle\Services;

use AdminBundle\Repositories\AdminRepository;
use Hyperf\Di\Annotation\Inject;
use AdminBundle\Repositories\SystemRolesPermissionsRepository;
use AdminBundle\Repositories\SystemRolesRepository;
use AdminBundle\Repositories\SystemRolesUserRepository;
use AdminBundle\Services\PermissionsService;
use AdminBundle\Services\AdminService;

/**
 * RolesService
 * 角色服务
 */
class RolesService
{
    /**
     * @Inject
     * @var PermissionsService
     */
    public $permissionsService;

    /**
     * getList
     * 条件获取角色列表
     * @param array $where 查询条件
     * @param array $order 排序条件
     * @param int $offset 偏移
     * @param int $limit 条数
     * @return mixed
     */
    public function getList($where = [], $page = 1, $pageSize = 20, $order = [])
    {
        $list = SystemRolesRepository::instance()->getList($where, ['*'], $page, $pageSize, $order);
        //对应权限id
        foreach ($list['list'] as &$item) {
            $item['permission'] = SystemRolesPermissionsRepository::instance()->where(['system_role_id'=>$item['id']])->pluck('system_permission_id');
        }
        unset($item);
        return $list;
    }

    /**
     * getPagesInfo
     * 获取分页信息
     * @param array $where
     * @return mixed
     */
    public function getPagesInfo($where = [])
    {
        $pageInfo = $this->systemRoleModel->getPagesInfo($where);

        return $pageInfo;
    }

    /**
     * saveRoles
     * 保存角色，构造数据，防止注入
     * 不接收数据库字段以外数据
     * @param $inputData
     * @return mixed
     */
    public function saveRoles($inputData)
    {
        $saveData = [];
        if (isset($inputData['id']) && $inputData['id']){
            $saveData['id'] = $inputData['id'];
        }

        if (isset($inputData['display_name']) && $inputData['display_name']){
            $saveData['display_name'] = $inputData['display_name'];
        }

        if (isset($inputData['name'])){
            $saveData['name'] = $inputData['name'];
        }

        if (isset($inputData['description'])){
            $saveData['description'] = $inputData['description'];
        }

        $result = SystemRolesRepository::instance()->saveData($saveData);

        return $result;
    }

    /**
     * getInfo
     * 根据id获取信息
     * @param $id
     * @return mixed
     */
    public function getInfo($id)
    {
        return SystemRolesRepository::instance()->find($id);
    }

    /**
     * deleteInfo
     * 根据id删除信息
     * @param $id
     * @return mixed
     */
    public function deleteInfo($id)
    {
        SystemRolesRepository::instance()->deleteByIds($id);

        return true;
    }

    /**
     * getRolePermissions
     * 获取角色的权限集合
     * @param $ids
     * @return array
     */
    public function getRolePermissions($ids)
    {
        $list = SystemRolesPermissionsRepository::instance()->getPermissionsByRolesIds($ids);
        $list = $this->handelPermissionsGroup($list);

        $allList = $this->getAllPermissions();
        foreach ($allList as $v) {
            if (!isset($list[$v['id']])) {
                $list[$v['id']] = [];
            }
        }

        $data = [
            'permissions_list' => $allList,
            'role_permissions' => $list,
        ];
        return $data;
        return $list;
    }

    /**
     * getAllPermissions
     * 获取所有权限treelist
     * User：YM
     * Date：2020/2/4
     * Time：下午10:05
     * @return array
     */
    public function getAllPermissions()
    {
        $list = $this->permissionsService->getPermissionsTreeList();

        return $list;
    }

    /**
     * handelPermissionsGroup
     * 将角色权限列表，按着权限父级分组
     * @param array $list
     * @return array
     */
    public function handelPermissionsGroup($list = [])
    {
        if (!$list) {
            return [];
        }

        $tmp = [];
        foreach ($list as $v) {
            $tmp[$v['parent_id']][] = $v['system_permission_id'];
        }

        return $tmp;
    }

    /**
     * deleteRolesPermissions
     * 根据roleid删除对应的信息。
     * 由于角色权限一对多，所以每一次角色权限修改后会先做删除操作
     * @param $id
     * @return mixed
     */
    public function deleteRolesPermissions($id)
    {
        $where = ['system_role_id'=> $id];
        SystemRolesPermissionsRepository::instance()->deleteByWhere($where);
        return true;
    }

    /**
     * saveRolesPermissions
     * 保存角色权限
     * @param array $data
     * @return mixed
     */
    public function saveRolesPermissions($data = [])
    {
        $saveData = [];
        $roleId = $data['id'] ?? 0;
        $tmp = $data['permissions_id'] ?? [];
        $time = date('Y-m-d H:i:s', time());
        $this->deleteRolesPermissions($roleId);
        foreach ($tmp as $v) {
            $saveData[] = ['system_role_id' => $roleId, 'system_permission_id' => $v, 'created_at' => $time, 'updated_at' => $time];
        }
        $this->saveRoles($data);
        $info = SystemRolesPermissionsRepository::instance()->saveManyData($saveData);
        // 删除用户组下对应用户的缓存权限，缓存菜单
        /*******        此段有问题                */
        // $ids = $this->getRoleUsers($roleId);
        // if ($ids) {
        //     flushAnnotationCache('admin-user-permission', $ids);
        //     flushAnnotationCache('admin-user-menu', $ids);
        // }
        /*******        此段有问题                */

        return $info;
    }

    /**
     * saveRolesUser
     * 保存用户对应角色
     * @param $data
     * @return mixed
     */
    public function saveRolesUser($data)
    {
        $info = SystemRolesUserRepository::instance()->saveData($data);
        
        
        /*******        此段有问题                */
        // 删除用户权限缓存
        // flushAnnotationCache('admin-user-permission', $data['user_id']);
        // 删除用户菜单缓存
        // flushAnnotationCache('admin-user-menu', $data['user_id']);
        /*******        此段有问题                */


        return $info;
    }

    /**
     * saveUserRoles
     * 保存用户对应的角色，一对多
     * @param $data
     * @return mixed
     */
    public function saveUserRoles(array $data)
    {
        return SystemRolesUserRepository::instance()->saveManyData($data);
    }

    /**
     * deleteRolesUser
     * 根据规则删除角色用户
     * @param $where
     * @return mixed
     */
    public function deleteRolesUser(array $where)
    {
        SystemRolesUserRepository::instance()->deleteByWhere($where);
        
        /*******        此段有问题                */
        // 删除用户权限缓存
        // flushAnnotationCache('admin-user-permission', $where['user_id']);
        // 删除用户菜单缓存
        // flushAnnotationCache('admin-user-menu', $where['user_id']);
        /*******        此段有问题                */

        return true;
    }

    /**
     * getRolesUserPagesInfo
     * 获取角色关联用户的分页信息
     * @param array $where
     * @return array
     */
    public function getRolesUserPagesInfo($where = [])
    {
        $pageInfo = $this->systemRolesUserModel->getPagesInfo($where);

        return $pageInfo;
    }

    /**
     * getRolesUserList
     * 获取角色关联用户的列表信息
     * @param array $where 条件
     * @param int $offset 偏移
     * @param int $limit 取值数量
     * @return mixed
     */
    public function getRolesUserList($where = [], $cols = ['*'], $page = 0, $pageSize = 0)
    {
        $list = SystemRolesUserRepository::instance()->getList($where, $cols, $page, $pageSize);

        return $list;
    }

    /**
     * getRoleUsers
     * 获取角色对应的用户的id集合
     * @param $roleId
     * @return array
     */
    public function getRoleUsers($roleId)
    {
        $where = ['system_role_id' => $roleId];

        $list = $this->getRolesUserList($where);
        $ids = array_pluck($list['list'], 'user_id');
        return $ids;
    }


    /**
     * getUserRoles
     * 获取用户对应的角色的id集合
     * @param $userId
     * @return array
     */
    public function getUserRolesId($userId)
    {
        $where = ['user_id' => $userId];

        $list = $this->getRolesUserList($where);
        $ids = array_pluck($list['list'], 'system_role_id');
        return $ids;
    }

    /**
     * getUserRoles
     * 获取用户对应的角色集合
     * @param $userId
     * @return array
     */
    public function getUserRoles($userId)
    {
        $ids = $this->getUserRolesId($userId);
        //获取角色信息
        $where['id'] = ['in', $ids];
        $list = SystemRolesRepository::instance()->getList($where, ['id', 'display_name'], 0, 0)['list'];
        return $list;
    }

    /**
     * getUsers
     * 获取角色关联的用户list
     * @param $inputData
     * @return array
     */
    public function getUsers($inputData, $page = 1, $pageSize = 20)
    {
        $list = $this->getRolesUserList($inputData, ['*'], $page, $pageSize);
        $totalCount = $list['total_count'];
        $list = $this->handleRolesUserList($list['list']);
        $data = [
            'total_count' => $totalCount,
            'list' => $list
        ];

        return $data;
    }

     /**
     * handleRolesUserList
     * 处理角色用户的列表
     * @param array $list
     * @return array
     */
    public function handleRolesUserList($list = [])
    {
        
        $tmp = [];
        foreach ($list as $v) {
            $tmp[] = AdminRepository::instance()->find($v['user_id'], ['id', 'account', 'mobile', 'email', 'username', 'created_at']);
        }

        return $tmp;
    }

    /**
     * searchUser
     * 角色添加用户，用户搜索
     * User：YM
     * Date：2020/2/4
     * Time：下午10:06
     * @param $inputData
     * @return array
     */
    public function searchUser($inputData)
    {
        $adminService = new AdminService();
        $list['list'] = [];
        if (isset($inputData['search']) && $inputData['search']) {
            $filter['username'] = ['like', '%' . $inputData['search'] . '%'];
            $ids = $this->getRoleUsers($inputData['role_id']);
            $filter['id'] = ['not_in', $ids];
            $list = $adminService->getList($filter, 0);
            foreach ($list['list'] as $k => $v) {
                $list['list'][$k]['value'] = $v['username'];
            }
        }

        return $list['list'];
    }
}